package com.sofwin.configer;

import com.sofwin.realm.MyRealm;
import com.sofwin.service.RoleService;
import com.sofwin.service.UserService;
import org.apache.shiro.authc.credential.CredentialsMatcher;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

/**
 * @packageName: com.sofwin.configer
 * @user: andyliu
 * @date: 2023/5/19 16:55
 * @email 115176513@qq.com
 * @description: TODO
 */
@Configuration
public class ShiroConfiger {
    @Autowired
    private UserService userService;
    @Autowired
    private RoleService roleService;
    @Bean
    public MyRealm myRealm(){
        MyRealm myRealm = new MyRealm();
        myRealm.setCredentialsMatcher(credentialsMatcher());
        myRealm.setRoleService(roleService);
        myRealm.setUserService(userService);
        return myRealm;
    }
    @Bean
    public CredentialsMatcher credentialsMatcher(){
        HashedCredentialsMatcher matcher = new HashedCredentialsMatcher();
        matcher.setHashIterations(10);// 设置加密时hash的次数
        matcher.setHashAlgorithmName("md5");// 设置加密时的算法
        matcher.setHashSalted(true); // 使用盐值加密
        return matcher;
    }

    // securityManager
    @Bean
    public DefaultWebSecurityManager defaultSecurityManager(){
        DefaultWebSecurityManager manager = new DefaultWebSecurityManager();
        // 缺Realm
        manager.setRealm(myRealm());
        return manager;
    }
    // realm

    @Bean("shiroFilter")
    public ShiroFilterFactoryBean shiroFilterFactoryBean(){
        ShiroFilterFactoryBean bean  = new ShiroFilterFactoryBean();
        bean.setSecurityManager(defaultSecurityManager());

        bean.setLoginUrl("/index.jsp");// 设置登录页面的请求
        bean.setUnauthorizedUrl("/login");// 设置哪些请求不需要进行身份认证
        Map<String,String> definitionMap = new HashMap<>();
        definitionMap.put("/**","authc"); // 所有资源都需要登录后访问（静态资源）
        definitionMap.put("/hplus/**","anon");
        definitionMap.put("/login","anon");
        definitionMap.put("/verification","anon");
        bean.setFilterChainDefinitionMap(definitionMap);
        return bean;
    }
}
